package particles;

import haxe.Timer;
import bpmjs.Stats;

class ParticlesWebGl
{
	static var instance : ParticlesWebGl;
	
	public static function main()
	{
		try
		{
			instance = new ParticlesWebGl();
		}
		catch (e : Dynamic)
		{
			trace("Error launching: " + e);
		}
	}
	
	public static function update()
	{
		instance.updateInternal();
	}
	
	var engine : Engine;
	 
	function new()
	{
		engine = new Engine(7000);
		
		updateEngine();	
	}
	
	function updateEngine()
	{
		engine.model.time = Date.now().getTime();
		engine.model.mouseX = 0;
		engine.model.mouseY = 0;
		engine.model.width = 1440;
		engine.model.height = 900;
		
		engine.update();
	}
	
	function updateInternal()
	{
		Stats.measureFPS();
		Stats.addMessage(":" + engine.model.particles.length);
		
		if(true)
		{
			//if (engine.model.particles.length < engine.model.maxCount)
				updateEngine();
			
			for(particle in engine.model.particles)
			{
				var alpha = 1 - (particle.age / particle.ageDead);
				if (particle.form == 1 || particle.form == 2)
					 alpha += Math.cos(particle.angle * 5) * 0.2;
					 
				var x = particle.x / 2;
				var y = particle.y / 2;
				drawStar(x, y, particle.angle, particle.form, particle.r / 255, particle.g / 255, particle.b / 255, alpha);
			}
		}
		else
		{
			for(i in 0...engine.model.maxCount)
			{
				var x = 400;
				var y = 250;
				drawStar(x, y, 0.5, 0, 1, 1, 1, 1);
			}
		}
	}
	
	static inline function drawStar(x : Float, y : Float, rotation : Float, formIndex : Float, r : Float, g : Float, b : Float, a : Float)
	{
		untyped __js__("drawStar")(x, y, rotation, formIndex, r, g, b, a);
	}	
	
}
